package com.cms.admin.action.order;

import com.cms.admin.util.PropertiesService;
import com.cms.admin.action.BaseAction;
import com.cms.admin.model.*;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.order.RegisterOrderActionService;
import com.cms.admin.service.order.RegisterOrderService;
import com.cms.admin.service.privilege.MedicalTreatRecordService;
import com.cms.admin.service.privilege.UserListService;
import com.cms.admin.util.Constants;
import com.opensymphony.xwork2.ModelDriven;
import io.rong.RongCloud;
import io.rong.models.GroupUser;
import io.rong.models.GroupUserQueryReslut;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by YYY on 2017/5/14.
 */
public class OrderManagerAction extends BaseAction implements ModelDriven<RegisterOrderExt> {

    private static String appKey=PropertiesService.getString("rong.appKey");
    private static String appSecret=PropertiesService.getString("rong.appSecret");

    private RegisterOrderService registerOrderService;
    private RegisterOrderActionService registerOrderActionService;
    private MedicalTreatRecordService medicalTreatRecordService;
    private TemplateService templateService;
    private UserListService userListService;

    private List<DepartmentList> departmentList;
    private RegisterOrderExt search = new RegisterOrderExt();
    private PageBean page;

    private String type;
    private Long UserID;
    private String time;
    private UserList userList;

    private Long registerID;
    private RegisterOrderExt registerOrder;
    private List<RegisterOrderAction> registerOrderActions;
    private MedicalTreatRecord medicalTreatRecord;

    public String ajaxQueryOrderList() {

        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        page = new PageBean(search.getCurrentPage(), search.getPageSize());
        
        
        System.out.println("Type:"+search.getType());
        if (-1 == search.getRunstatusid()) {
        	
        	 List<Integer> runstatusids = new ArrayList<Integer> ();
        	 
        	//查询所有进行中订单 
        	if (search.getType().equals("1")) 
        	{
        		runstatusids.add(1);
        		runstatusids.add(2);
        		runstatusids.add(3);
        		search.setRunstatusids(runstatusids);
        	//查询所有咨询完订单	
			}else if (search.getType().equals("2")) {
				runstatusids.add(4);
        		runstatusids.add(5);
        		runstatusids.add(6);
        		search.setRunstatusids(runstatusids);
			}
            search.setRunstatusid(null);
        }
        if ("-1".equals(search.getRegisterguideid())) {
            search.setRegisterguideid(null);
        }
        List<RegisterOrder> registerOrderList = registerOrderService.queryOrderList(page, search);

        String res = null;


        try {
            res = getQueryResult(registerOrderList, page);
            JSONObject o = new JSONObject();
            o.put("pageCount", page.getTotalPage());
            o.put("content", res);
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryUnGoingOrder", e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    public String ajaxQueryOrderMember()
    {
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        try {
            GroupUserQueryReslut reslut=rongCloud.group.queryUser(String.valueOf(registerID));
            if (reslut.getCode()==200)
            {
                List<GroupUser> groupUsers=reslut.getUsers();
                if (groupUsers!=null&&groupUsers.size()>0)
                {
                    List<QueryUserResp> queryUserResps=new ArrayList<QueryUserResp>();
                    for (GroupUser groupUser:groupUsers)
                    {
                        QueryUserReq req=new QueryUserReq();
                        req.setUserId(groupUser.getId());
                        String response=serverPostHead("queryUser", req);
                        JSONObject jsonObject=JSONObject.fromObject(response);
                        QueryUserResp resp= (QueryUserResp) JSONObject.toBean(jsonObject,QueryUserResp.class);
                        resp.setUserId(groupUser.getId());
                        queryUserResps.add(resp);
                    }

                    String resultString=getMemberQueryResult(queryUserResps);
                    JSONObject o = new JSONObject();
                    o.put("content", resultString);
                    o.put("errorCode",0);
                    return  ajaxJson(o);

                }else
                {
                    return ajaxJsonErrorMessage("查询不到相关成员信息！");
                }

            }else
            {
                JSONObject o = new JSONObject();
                o.put("errorCode",-1);
                o.put("errorMsg","查询融云群组成员失败");
                return ajaxJson(o);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject o = new JSONObject();
            o.put("errorCode",-1);
            o.put("errorMsg","系统错误！");
            return ajaxJson(o);
        }

    }

    public String ajaxQueryOrderDetail() {
        registerOrder = registerOrderService.queryOrderDetail(registerID);
        registerOrderActions = registerOrderActionService.getRegisterOrderActionByRegisterid(registerID);
        List<MedicalTreatRecord> medicalTreatRecords = medicalTreatRecordService.queryMedicalTreatRecordByRegisterid(registerID);
        if (null != medicalTreatRecords && medicalTreatRecords.size() > 0) {
            medicalTreatRecord = medicalTreatRecords.get(0);
        }
        return SUCCESS;
    }

    
 
    
	public String ajaxQueryUser() {
	       LOG.info("Start ArticleAction process,method is ajaxQuery");
	        LOG.debug("Action is:" + search.getAction());
	        
	        //UserID
	        if (null != UserID) {
	                JSONObject param = new JSONObject();
	                param.put("userId", UserID);
	                String responseString = serverPostHead("queryUser", param);
	                JSONObject jsonObject = JSONObject.fromObject(responseString);
	                
	                //leftTime01
	                JSONObject o = new JSONObject();
	                o.put("user", jsonObject.get("user"));
	                o.put("errorCode",0);
	                o.put("errorMsg","success");

	                System.out.println(jsonObject.get("user"));
	                return ajaxJson(o);
	                
	        } else {
	            JSONObject o = new JSONObject();
	            o.put("errorCode", -1);
	            o.put("errorMsg", "错误");
	            return ajaxJson(o);
	        }
	}
	
	//appId=12345679&version=1.0&method=payControllerDoc&timestamp=20121212154843&uuId=05ae94531ed53d89ff5da71d6f2ad780366a4eb9&memberid=1&
	//sign=2976b2f3db9530e0de8097c1c912550f&lang=zh-Hans000000000
	//{"orderId":"1000357288","type":"1","userId":"489180","cardType":2,"payType":1,"times":12}
	public String ajaxCutPament() {
	       LOG.info("Start ArticleAction process,method is ajaxQuery");
	        LOG.debug("Action is:" + search.getAction());
	        
	        //UserID
	        if (null != UserID) {
	                JSONObject param = new JSONObject();
	                param.put("userId", UserID);
	                param.put("orderId", registerID);
	                param.put("times", time);
	                param.put("payType",1);
	                param.put("cardType", 2);
	                param.put("type", 1);
	                
	                if (StringUtils.isNumeric(time)) {
	                	param.put("times", time);
					}else{
						 JSONObject o = new JSONObject();
				         o.put("errorCode", -1);
				         o.put("errorMsg", "次数参数错误");
				         return ajaxJson(o);
					}
	                
	                String responseString = serverPostHead("payControllerDoc", param);
	                JSONObject jsonObject = JSONObject.fromObject(responseString);
	                
	                JSONObject o = new JSONObject();
	                o.put("errorCode",0);
	                o.put("errorMsg","success");

	                System.out.println(jsonObject.get("user"));
	                return ajaxJson(o);
	                
	        } else {
	            JSONObject o = new JSONObject();
	            o.put("errorCode", -1);
	            o.put("errorMsg", "错误");
	            return ajaxJson(o);
	        }
	}
	
    
    public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	private String getMemberQueryResult(List<QueryUserResp> queryUserResps) throws Exception
    {
        HashMap map = new HashMap();
        map.put("queryUserRespList", queryUserResps);
        map.put("resPath", PropertiesService.getString("res.path"));
        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_ORDER_MEMBER_QUERY_RESULT, map);
        return result;
    }
    private String getQueryResult(List<RegisterOrder> registerOrderList, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("registerOrderList", registerOrderList);
        map.put("page", page);
        map.put("basePath", getBasePath());

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_REGISTERORDER_QUERY_RESULT, map);
        return result;
    }


    public String getOrderSearchHeader() {


        return "getHeader";
    }

    public String getOrderList() {

        if (null != UserID) {
            userList = userListService.getById(UserID);
        }
        return "success";
    }

    @Override
    public RegisterOrderExt getModel() {
        return search;
    }

    public RegisterOrderService getRegisterOrderService() {
        return registerOrderService;
    }

    public void setRegisterOrderService(RegisterOrderService registerOrderService) {
        this.registerOrderService = registerOrderService;
    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    public RegisterOrderExt getSearch() {
        return search;
    }

    public void setSearch(RegisterOrderExt search) {
        this.search = search;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Long getUserID() {
        return UserID;
    }

    public void setUserID(Long userID) {
        UserID = userID;
    }

    public UserList getUserList() {
        return userList;
    }

    public void setUserList(UserList userList) {
        this.userList = userList;
    }

    public UserListService getUserListService() {
        return userListService;
    }

    public void setUserListService(UserListService userListService) {
        this.userListService = userListService;
    }

    public Long getRegisterID() {
        return registerID;
    }

    public void setRegisterID(Long registerID) {
        this.registerID = registerID;
    }

    public RegisterOrderExt getRegisterOrder() {
        return registerOrder;
    }

    public void setRegisterOrder(RegisterOrderExt registerOrder) {
        this.registerOrder = registerOrder;
    }

    public List<RegisterOrderAction> getRegisterOrderActions() {
        return registerOrderActions;
    }

    public void setRegisterOrderActions(List<RegisterOrderAction> registerOrderActions) {
        this.registerOrderActions = registerOrderActions;
    }

    public RegisterOrderActionService getRegisterOrderActionService() {
        return registerOrderActionService;
    }

    public void setRegisterOrderActionService(RegisterOrderActionService registerOrderActionService) {
        this.registerOrderActionService = registerOrderActionService;
    }

    public MedicalTreatRecord getMedicalTreatRecord() {
        return medicalTreatRecord;
    }

    public void setMedicalTreatRecord(MedicalTreatRecord medicalTreatRecord) {
        this.medicalTreatRecord = medicalTreatRecord;
    }

    public MedicalTreatRecordService getMedicalTreatRecordService() {
        return medicalTreatRecordService;
    }

    public void setMedicalTreatRecordService(MedicalTreatRecordService medicalTreatRecordService) {
        this.medicalTreatRecordService = medicalTreatRecordService;
    }
}
